#!/etc/bin/env python2.6

import os
import os.path
import zipfile
from xml.dom import minidom

class ebook:
    def __init__(self, fname):
        self.fileName = fname
        zip = zipfile.ZipFile(fname)
        metafile = zip.read('META-INF/container.xml')
        xmldoc = minidom.parseString(metafile)
        rootNode = xmldoc.documentElement
        node = rootNode.getElementsByTagName('rootfiles')[0]
        node = node.getElementsByTagName('rootfile')[0]
        cfname = node.getAttribute('full-path')

        cf = zip.read(cfname)
        xmldoc = minidom.parseString(cf)
        rootNode = xmldoc.documentElement
        node = rootNode.getElementsByTagName('metadata')[0]

        title = node.getElementsByTagName('dc:title')[0]
        self.title = title.childNodes[0].data
        #print('title="{0}"'.format(title))

        creator = node.getElementsByTagName('dc:creator')[0]
        self.creator = creator.childNodes[0].data
        #print('creator="{0}"'.format(creator))

def isEBookFile(fname):
    (fn, ext) = os.path.splitext(fname)
    ext = ext.lower()
    if ext == '.epub':
        return True
    if ext == '.epu':
        return True
    return False

def getListOfEBookFiles(dir):
    subdirlist = []
    res = []
    for file in os.listdir(dir):
        file = os.path.join(dir, file)
        if os.path.islink(file):
            pass
        if os.path.isdir(file):
            subdirlist.append(file)
        else:
            if isEBookFile(file):
                res.append(file)

    for subdir in subdirlist:
        subfiles = getListOfEBookFiles(subdir)
        for subfile in subfiles:
            if isEBookFile(subfile):
                res.append(subfile)

    return res
        
